package com.jwell.panprovider.ui.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.jwell.cargoapp.ui.base.MVPBaseActivity
import com.jwell.panprovider.R
import com.jwell.panprovider.contract.SearchContract
import com.jwell.panprovider.entity.InlineBean
import com.jwell.panprovider.entity.SearchBen
import com.jwell.panprovider.entity.SearchDriverBean
import com.jwell.panprovider.presenter.SearchPresenter
import com.jwell.panprovider.ui.adapter.SearchAdapter
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.toolbar.*

/**
 * 各种搜索界面
 */
class SearchActivity : MVPBaseActivity<SearchPresenter>(), SearchContract.View, View.OnClickListener {


    private var listData = ArrayList<Any>()
    private var adapter = SearchAdapter(listData)
    private var canBack = false
    private var canInput = false
    private var searchType = -1
    //选择司机
    private var selectedDriver: SearchDriverBean? = null
    //司机position
    private var driverPosition = -1
    //选择的货物是否可以标证除皮
    private var isOutOfSkin = false
    //是否自动搜索，默认为true，点击列表项后为false，输入框输入后为true
    private var canSearch = true
    private var id = -1
    override fun createPresenter(): SearchPresenter? {
        return SearchPresenter()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        toolbar_right_text_save.visibility = View.VISIBLE
        canInput = when (intent?.extras?.getBoolean("canInput")) {
            true -> true
            else -> false
        }
        intent?.extras?.getInt("type")?.let {
            searchType = it
        }
        intent?.extras?.getInt("driverPosition")?.let {
            driverPosition = it
        }
        when (searchType) {
            0 -> {
                initToolBar("物资名称", true, null)
                if (canInput) {
                    ditText.hint = "请输入或搜索物资名称"
                } else {
                    ditText.hint = "请搜索物资名称"
                }
                presenter?.appGetProList(null)
            }
            1 -> {
                initToolBar("发货单位", true, null)
                if (canInput) {
                    ditText.hint = "按单位名称/编码搜索或直接输入"
                } else {
                    ditText.hint = "按单位名称/编码搜索"
                }
                presenter?.appGetUnitInformationList(null)
            }
            2 -> {
                initToolBar("收货单位", true, null)
                if (canInput) {
                    ditText.hint = "按单位名称/编码搜索或直接输入"
                } else {
                    ditText.hint = "按单位名称/编码搜索"
                }
                presenter?.appGetUnitInformationList(null)
            }
            3 -> {
                initToolBar("司机搜索", true, null)
                if (canInput) {
                    ditText.hint = "请输入或搜索驾驶员姓名/电话"
                } else {
                    ditText.hint = "请搜索驾驶员姓名/电话"
                }
                presenter?.getDriverList(null)
            }
            4 -> {
                initToolBar("选择合同号", true, null)
                canInput = false
                canBack = true
                ditText.hint = "搜索合同号/物资名称/供应商"
                presenter?.getContractList(null)
            }
        }
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)
        setListener()

    }

    private fun setListener() {
        adapter.setOnItemOnClickLisenter(object : SearchAdapter.OnItemOnClickListener {
            override fun onClick(position: Int) {
                if (listData[position] is SearchBen) {
                    isOutOfSkin = (listData[position] as SearchBen).isOutOfSkin
                    (listData[position] as SearchBen).id?.let {
                        id = it
                    }
                    canSearch = false
                    ditText.setText((listData[position] as SearchBen).orgName)
                    canBack = true
                }
                if (listData[position] is SearchDriverBean) {
                    selectedDriver = listData[position] as SearchDriverBean
                    var driverName = selectedDriver?.driverName ?: ""
                    var driverPhone = selectedDriver?.driverPhone ?: ""
                    canSearch = false
                    ditText.setText(driverName)
                    canBack = true
                }
            }
        })
        ditText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                canBack = canInput
                isOutOfSkin = false
                if (s?.toString().isNullOrEmpty()) {
                    image_delete.visibility = View.GONE
                } else {
                    image_delete.visibility = View.VISIBLE
                }
                if (canSearch) {
                    when (searchType) {
                        0 -> {
                            presenter?.appGetProList(s?.toString())
                        }
                        1 -> {
                            presenter?.appGetUnitInformationList(s?.toString())

                        }
                        2 -> {
                            presenter?.appGetUnitInformationList(s?.toString())
                        }
                        3 -> {
                            presenter?.getDriverList(s?.toString())
                        }
                    }
                }
                canSearch = true
            }
        })
        image_delete.setOnClickListener {
            ditText.setText("")
        }
        toolbar_right_text_save.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.toolbar_right_text_save -> {
                if (searchType != 4 && ditText.text.isNullOrEmpty()) {
                    return
                }
                if (canBack) {//返回
                    var intent = Intent()
                    if (searchType == 0 || searchType == 1 || searchType == 2 || searchType == 3) {
                        intent.putExtra("input", ditText.text.toString())
                        intent.putExtra("id", id)
                        if (searchType == 0) {//选择货物
                            //是否可以标证除皮
                            intent.putExtra("isOutOfSkin", isOutOfSkin)
                        }
                        if (searchType == 3 && driverPosition > -1) {
                            intent.putExtra("driverPosition", driverPosition)
                            var bundle = Bundle()
                            if (listData.isEmpty()) {//没有搜索到司机
                                selectedDriver = SearchDriverBean()
                                if (ditText.text.toString().startsWith("1")) {
                                    if (ditText.text.toString().length == 11) {
                                        selectedDriver?.driverPhone = ditText.text.toString()
                                    } else {
                                        toast("请输入正确的手机号码！")
                                        return
                                    }
                                } else {
                                    selectedDriver?.driverName = ditText.text.toString()
                                }
                                selectedDriver?.driverId = 0
                            }
                            if (selectedDriver == null) {//没有选择司机
                                selectedDriver = SearchDriverBean()
                                if (ditText.text.toString().startsWith("1")) {
                                    if (ditText.text.toString().length == 11) {
                                        selectedDriver?.driverPhone = ditText.text.toString()
                                    } else {
                                        toast("请输入正确的手机号码！")
                                        return
                                    }
                                } else {
                                    selectedDriver?.driverName = ditText.text.toString()
                                }
                                selectedDriver?.driverId = 0
                            }
                            bundle.putSerializable("selectedDriver", selectedDriver)
                            intent.putExtras(bundle)
                        }
                    } else if (searchType == 4) {
                        var checkedInLineList = ArrayList<InlineBean>()
                        var bundle = Bundle()
                        listData.filterIsInstance<InlineBean>().filterTo(checkedInLineList) { it.checked }
                        bundle.putSerializable("selectedInLineList", checkedInLineList)
                        intent.putExtras(bundle)
                        if (checkedInLineList.isEmpty()) {
                            toast("您还没有任何选择")
                            return
                        }
                    }
                    setResult(Activity.RESULT_OK, intent)
                    returnActivity()
                } else {
                    toast("该内容只能选择！")
                }
            }
        }
    }

    override fun showSearchBenList(data: List<Any>) {
        listData.clear()
        listData.addAll(data)
        adapter.notifyDataSetChanged()
    }
}
